const express = require('express')
const router = express.Router()
const PlayModel = require('../models/play')
const checkLogin = require('../middlewares/check').checkLogin

// GET /play/:playId/edit 更新ep
router.get('/:playId/edit', checkLogin, (req, res, next) => {
  const playId = req.params.playId
  const author = req.session.user._id

  PlayModel.getRawPlayById(playId)
    .then((ep) => {
      if (!ep) {
        throw new Error('不存在')
      }
      if (author.toString() !== ep.author._id.toString()) {
        throw new Error('权限不足')
      }
      res.render('ac/play/edit', {
        ep
      })
    })
    .catch(next)
})

// POST play/:playId/edit 更新分集
router.post('/:playId/edit', checkLogin, (req, res, next) => {
  const author = req.session.user._id
  const { playId } = req.params
  const { title, subTitle, url, tags, source, sort } = req.fields

  // 校验参数
  try {
    if (!title.length) {
      throw new Error('请填写标题')
    }
  } catch (e) {
    req.flash('error', e.message)
    return res.redirect('back')
  }

  const ep = { author, title, subTitle, url, tags, source, sort: parseInt(sort) }

  PlayModel.getRawPlayById(playId)
    .then((data) => {
      if (!data) {
        throw new Error('该分集不存在')
      }
      if (author.toString() !== data.author._id.toString()) {
        throw new Error('权限不足')
      }
      PlayModel.updatePlayById(playId, ep)
        .then(() => {
          console.log(data, '---------------------------------------data')
          req.flash('success', '编辑成功')
          // 编辑成功后跳转到上一页
          res.redirect(`/ep/${data.epId}`)
        })
        .catch(next)
    })
})

module.exports = router
